﻿using DataChangeTools.SplashModule.Events;
using DataChangeTools.SplashModule.Interfaces;
using DataChangeTools.SplashModule.ViewModels;
using DataChangeTools.SplashModule.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace DataChangeTools.SplashModule
{
    public class Module : IModule
    {

        [Dependency]
        public IUnityContainer Container { get; set; }

        [Dependency]
        public IEventAggregator EventAggregator { get; set; }

        [Dependency]
        public IShell Shell { get; set; }

        private AutoResetEvent WaitForCreation { get; set; }


        public void OnInitialized(IContainerProvider containerProvider)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() =>
            {
                Shell.Show();
                EventAggregator.GetEvent<CloseSplashEvent>().Publish(new CloseSplashEvent());
            }));

            WaitForCreation = new AutoResetEvent(false);

            void ShowSplash()
            {
                Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() =>
                {
                    Container.RegisterType<SplashViewViewModel, SplashViewViewModel>();
                    Container.RegisterType<SplashView, SplashView>();

                    var splash = Container.Resolve<SplashView>();
                    EventAggregator.GetEvent<CloseSplashEvent>().Subscribe(e => splash.Dispatcher.BeginInvoke((Action)splash.Close), ThreadOption.PublisherThread, true);

                    splash.Show();

                    WaitForCreation.Set();
                }));

                Dispatcher.Run();
            }

            var thread = new Thread((ThreadStart)ShowSplash) { Name = "Splash Thread", IsBackground = true };
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            WaitForCreation.WaitOne();
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //containerRegistry.RegisterForNavigation<AutoUpdaterView, AutoUpdaterViewModel>();

            //containerRegistry.RegisterDialog<AutoUpdaterView>("AutoUpdaterView");
        }

    }
}
